package com.rt.easyjava.base.modules.shortToken.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rt.easyjava.base.modules.shortToken.dto.ShortTokenDto;
import com.rt.easyjava.base.modules.shortToken.service.beanService.ShortTokenService;
import com.rt.easyjava.common.base.Result;
import com.rt.easyjava.common.config.dozer.MyMapper;
import com.rt.easyjava.common.utils.others.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
* 业务前端控制器
* 1，定义具有业务含义的控制方法：可以复制beanController中的相关方法，重命名成具有业务含义，删除beanController中没有使用的方法，精简代码。
* 2，用户信息可直接形参获取：String (_userId，_loginName，_userName，_companyId，userDetailsJson)
* @author wuxiaoyong
* @since 2022-05-04
*/
@Slf4j
@Api(tags = "ShortTokenBizController - 业务控制类")
@RequestMapping("/innerService/shortTokenBiz")
@Controller
public class ShortTokenBizController {
    @Autowired
    protected MyMapper mapper;
    @Autowired
    protected ShortTokenService shortTokenService;


    //@PreAuthorize("hasAuthority('shortToken:query')")
    @ApiOperation("selectBy")
    @GetMapping(value = "/selectBy")
    @ResponseBody
    public String selectBy(String jti){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("jti", jti);
        Result r = shortTokenService.selectBy(queryWrapper);
        List<ShortTokenDto> shortTokenDtoList = r.getList();
        if (shortTokenDtoList==null || shortTokenDtoList.size()==0) {
            return null;
        }
        ShortTokenDto shortTokenDto = shortTokenDtoList.get(0);
        return shortTokenDto.getToken();
    }


    /**
     * 保存： accessToken， refreshToken
     * @return
     */
    //@PreAuthorize("hasAuthority('shortToken:create')")
    @ApiOperation("新增对象")
    @PostMapping(value = "/create")
    @ResponseBody
    public Result create(@RequestBody Map map){
        String jti = (String) map.get("jti");
        String accessToken = (String) map.get("accessToken");
        if (StringUtils.isNull(jti)) {
            return Result.builder().fault("jti is null");
        }
        if (StringUtils.isNull(accessToken)) {
            return Result.builder().fault("accessToken is null");
        }

        ShortTokenDto shortTokenDto = new ShortTokenDto();
        shortTokenDto.setJti(jti);
        shortTokenDto.setToken(accessToken);
        return shortTokenService.create(shortTokenDto);
    }

}
